<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{text-align: center;}
    </style>
</head>

<body>
    <div>
    <h3>留言板</h3>
    标题：<input type="text" id="txt">
    <button id="btn">添加</button>
    <ul>

    </ul>
    <br/>
    <span></span>
    </div>
    <script>
            // var time = `<span> 发表时间：${sj()}</span>`
            //  document.getElementsByTagName('span')[0].innerHTML=time
        
         function sj(){
             var d =new Date();
            // console.log(d);
             var year = d.getFullYear();
             var yue = d.getMonth()+1;
             var tian = d.getDate();
             var shi = d.getHours();
             var fen = d.getMinutes();
             var miao =d.getMinutes();
            return  year + "-" + yue + "-" + tian + " " + shi + ":" + fen + ":" + miao
            }

            function fangfa() {
            var kt = localStorage.getItem('list')?? ""  //空值合并运算符 判断应用里的localStorage是否为空
           // console.log(kt)
            if (JSON.parse(kt)) { //如果应用里的localStorage不为空，则将输入框的内容转为数组，供页面识别
                var kz = JSON.parse(kt) //将输入框里的数组定义给一个变量
                var str = "" //建一个新的空数组
                for (let i in kz) { //遍历循环输入框里的数组
                    str += `<li>${kz[i].title}<br/>${kz[i].date}&emsp;<button onclick="del(${i})">删除</button></li>` //将内容以列表的形式转给新的数组
                }
                document.getElementsByTagName('ul')[0].innerHTML = str //在ul中输出数组
            }

        }
        function del(index){
            var data = JSON.parse(localStorage.getItem('list')) 
            data.splice(index,1);
            localStorage.setItem('list',JSON.stringify(data))
            fangfa()

        }

        window.onload = function () {
            document.getElementById("btn").onclick = function () {
                if(localStorage.getItem('list')==null){ //判断应用里的localStorage是否为空
                    localStorage.list=JSON.stringify([]) //若为空，则获取里面的值转化为数组，里面的值是由输入框输入值获取=》stringify([])
                }
                var t = document.getElementById("txt").value; //获取输入框的值
                var hq = JSON.parse(localStorage.getItem('list')); //将应用的localStorage值 转化为数组(数组里的值是以键值对的形式存在，{名：值},{名：值} )
                console.log(hq)
                hq.unshift({title:t,date:sj()}) //在应用的localStorage 头部添加新的内容，{名：值}数组里对象的格式
                hq = JSON.stringify(hq) //将数组转字符串，供应用里的localStorage识别
                localStorage.setItem('list', hq) //将输入框里的内容转到应用里，以key和key的值存在
                fangfa() //以列表的形式展示
               
            }
        }

    
    </script>
</body>

</html>